package com.kabigon.learning;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TtlWrapperDemo {
    //private static TransmittableThreadLocal<String> userContext = new TransmittableThreadLocal<>();
    private static ThreadLocal<String> userContext = new ThreadLocal<>();

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(3);

        for (int i = 1; i <= 3; i++) {
            final int userId = i;
            executorService.submit(() -> {
                userContext.set("User" + userId);

                System.out.println("Thread " + Thread.currentThread().getId() +
                        " has user context: " + userContext.get());

                // 模拟处理请求，可能涉及到其他方法
                processRequest();

                userContext.remove();
            });
        }

        executorService.shutdown();
    }

    private static void processRequest() {
        // 在业务逻辑中获取当前线程的用户身份信息
        System.out.println("Processing request in thread " + Thread.currentThread().getId() +
                " with user context: " + userContext.get());

        // 模拟复杂业务，可能涉及到其他方法
        performBusinessLogic();
    }

    private static void performBusinessLogic() {
        // 在这里同样可以获取到正确的用户身份信息
        System.out.println("Performing business logic in thread " + Thread.currentThread().getId() +
                " with user context: " + userContext.get());
    }
}